﻿using System;

namespace HCore
{
    public class StateMachine<T>
    {
        private readonly T _owner;
        private State<T> _currentState;
        private State<T> _globalState;

        public StateMachine(T owner)
        {
            _owner = owner;
            _currentState = null;
        }

        public void Update()
        {
            _globalState?.Execute();
            _currentState?.Execute();
        }

        public void ChangeState<V>() where V : State<T>
        {
            State<T> state = (State<T>) Activator.CreateInstance(typeof(V), _owner);

            _currentState?.Exit();

            _currentState = state;

            _currentState?.Enter();
        }

        public void SetGlobalState<V>() where V : State<T>
        {
            State<T> state = (State<T>) Activator.CreateInstance(typeof(V), _owner);

            _globalState?.Exit();

            _globalState = state;

            _globalState?.Enter();
        }

        public bool isInState(Type t)
        {
            return t == _currentState.GetType();
        }

        public void Dispose()
        {
            _globalState?.Exit();
            _globalState = null;
            _currentState?.Exit();
            _currentState = null;
        }
    }
}